package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.FreemarkerService;
import com.heima.common.exception.CustomException;
import com.heima.file.service.impl.MinIOFileTemplate;
import com.heima.model.common.dtos.ArticleDto;
import com.heima.model.common.dtos.ArticleHomeDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticle;
import com.heima.model.common.pojos.article.ApArticleConfig;
import com.heima.model.common.pojos.article.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApArticleContentMapper contentMapper;
    @Autowired
    private ApArticleConfigMapper configMapper;
    @Autowired
    private FreemarkerService freemarkerService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 查询首页数据
     *
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult selectLoad(ArticleHomeDto dto, Integer type) {

        //校验参数
        if (dto == null || (type != 1 && type != 2)) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //数据处理
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getSize() <= 1 || dto.getSize() > 50) {
            dto.setSize(10);
        }

        //查询数据库
        List<ApArticle> apArticles = apArticleMapper.selectLoad(dto, type);

        return ResponseResult.okResult(apArticles);
    }

    /**
     * 保存或者修改文章信息
     *
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveOrUpdateArticle(ArticleDto articleDto) {
        if (articleDto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(articleDto, article);

        //判断文章是新增还是修改
        if (articleDto.getId() == null) { //新增操作
            //1.保存文章信息 ap_article
            apArticleMapper.insert(article);
            //获取保存后文章id
            Long articleId = article.getId();
            articleDto.setId(articleId);

            //2.保存文章配置信息 ap_article_config
            ApArticleConfig apArticleConfig = new ApArticleConfig(articleId);
            configMapper.insert(apArticleConfig);

            //3.保存文章内容 ap_article_content
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(articleId);
            articleContent.setContent(articleDto.getContent());
            contentMapper.insert(articleContent);

        } else { //更新操作
            //1. 更新文章信息 ap_article
            apArticleMapper.updateById(article);

            //2. 修改文章内容信息：ap_article_content
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(article.getId());
            articleContent.setContent(articleDto.getContent());

            //update ap_article_content set ? ,? where article_id = ?
            contentMapper.update(articleContent,
                    Wrappers.<ApArticleContent>lambdaUpdate().eq(ApArticleContent::getArticleId, articleContent.getArticleId()));
        }

        //todo: 生成文章详情页： freemarker + minio
        freemarkerService.generateDetailHtml(articleDto);

        //同步到es索引库中
        kafkaTemplate.send("save_into_es", JSON.toJSONString(articleDto));

        //将保存后文章id返回
        return ResponseResult.okResult(article.getId());
    }

    @Override
    public void downOrUp(Map map) {
        boolean isDown = true;

        if ((int)map.get("enable") == 1) { //表示要上架
            isDown = false;
        }

        ApArticleConfig articleConfig = new ApArticleConfig();
        articleConfig.setArticleId((long)map.get("articleId"));
        //更新配置
        configMapper.update(articleConfig,Wrappers.<ApArticleConfig>lambdaUpdate()
                .set(ApArticleConfig::getIsDown,isDown)
                .eq(ApArticleConfig::getArticleId,articleConfig.getArticleId()));
    }

}
